package cn.csc.module.order.mq.producer;

import cn.csc.framework.mq.core.bus.AbstractBusProducer;
import cn.csc.module.order.dal.dataobject.item.OrderItemDO;
import cn.csc.module.order.message.OrderSubmitMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户支付成功后发送下单消息
 * topic: order_submit
 * @author liuchuang
 * @version 1.0
 * @date 2024/7/30 9:42
 * @modify
 */
@Slf4j
@Component
public class OrderSubmitProducer extends AbstractBusProducer {

    @Resource
    private StreamBridge streamBridge;

    /**
     * 发送 {@link OrderSubmitMessage} 消息
     *
     * @param list 订单子项列表
     */
    public Boolean sendOrderSubmitMessage(List<OrderItemDO> list) {
        log.info("sendOrderSubmitMessage订单支付成功发送消息：{}",list);
        List<OrderSubmitMessage> collect = list.stream().map(o -> {
            OrderSubmitMessage orderMessage = new OrderSubmitMessage();
            orderMessage.setUserId(o.getUserId());
            orderMessage.setOrderId(o.getOrderId());
            orderMessage.setOrderItemId(o.getId());
            orderMessage.setAmount(o.getSpuTotalAmount());
            orderMessage.setCategoryId(o.getCategoryId());
            orderMessage.setPayTime(o.getPayTime());
            orderMessage.setOrderStatus(o.getOrderStatus());
            return orderMessage;
        }).collect(Collectors.toList());


        Message<List<OrderSubmitMessage>> message = MessageBuilder.withPayload(collect)
                // 设置ORIGIN_MESSAGE_ID
                .setHeader(MessageConst.PROPERTY_ORIGIN_MESSAGE_ID, list.get(0).getId())
                .build();
        return streamBridge.send("orderSubmit-out-0", message);
    }


}
